<template>
  <div class="app-container">
    <!-- <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="课程名称" prop="courseName">
        <el-input v-model="queryParams.courseName" placeholder="请输入课程名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="课程状态" clearable>
          <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:res:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-if="refreshTable" v-loading="loading" :data="tableData" row-key="id" :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column prop="courseName" label="课程名称" :show-overflow-tooltip="true" width="160"></el-table-column>
      <el-table-column prop="courseUrl" label="视频ID" width="300" align="center" :show-overflow-tooltip="true"></el-table-column>
      <!-- <el-table-column prop="permission" label="权限标识" align="center" :show-overflow-tooltip="true"></el-table-column> -->
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="courseSort" label="排序" width="60"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:res:update']">修改</el-button>
          <el-button type="text" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:res:add']">新增</el-button>
          <el-button type="text" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:res:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改课程对话框 -->
    <el-dialog :title="title" v-model="open" width="680px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级课程">
              <el-tree-select
                v-model="form.parentId"
                :data="resOptions"
                :check-strictly="true"
                :props="{ value: 'id', label: 'courseName', children: 'children' }"
                value-key="id"
                placeholder="选择上级课程"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="课程类型" prop="resType">
              <el-radio-group v-model="form.resType">
                <el-radio label="目录">目录</el-radio>
                <el-radio label="页面">页面</el-radio>
                <el-radio label="按钮">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="课程名称" prop="courseName">
              <el-input v-model="form.courseName" placeholder="请输入课程名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="courseSort">
              <el-input-number v-model="form.courseSort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-input v-model="form.courseUrl" placeholder="请输入视频ID" maxlength="100" />
              <template #label>
                <span>
                  <el-tooltip content="例如：腾讯视频 B站地址" placement="top">
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  视频地址
                </span>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="res">
import { createOne, deleteOne, queryOne, queryList, updateOne } from "@/api/course";

const { proxy } = getCurrentInstance();
// const { sys_show_hide, sys_normal_disable } = proxy.useDict("sys_show_hide", "sys_normal_disable");
const sys_normal_disable = ref([
  {
    value: 1,
    label: "启用",
  },
  {
    value: 0,
    label: "未启用",
  },
]);
const tableData = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const resOptions = ref([]);
const isExpandAll = ref(false);
const refreshTable = ref(true);

const data = reactive({
  form: {
    id: undefined,
    courseName: undefined,
    courseUrl: undefined,
    parentId: undefined,
    courseSort: 0,
  },
  queryParams: {
    parentId: undefined,
    sortBy: "courseSort",
    pageNum: 1,
    pageSize: 999,
  },
  rules: {
    courseName: [{ required: true, message: "课程名称不能为空", trigger: "blur" }],
    courseSort: [{ required: true, message: "课程顺序不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 修改状态
function handleStatusChange(row) {
  const data = row;
  let text = row.status === 0 ? "停用" : "启用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.courseName + "吗?")
    .then(function () {
      return updateOne(data);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
}

/** 查询课程列表 */
function getList() {
  loading.value = true;
  queryList(queryParams.value).then((response) => {
    response.content.forEach((element) => {
      element.parentId = element.parent?.id;
    });
    tableData.value = proxy.handleTree(response.content, "id");
    loading.value = false;
  });
}
/** 查询课程下拉树结构 */
function getTreeselect() {
  resOptions.value = [];
  queryList(queryParams.value).then((response) => {
    response.content.forEach((element) => {
      element.parentId = element.parent?.id;
    });
    const res = { id: 0, courseName: "主分支", children: [] };
    res.children = proxy.handleTree(response.content, "id");
    resOptions.value.push(res);
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    courseName: undefined,
    courseUrl: undefined,
    parentId: undefined,
    courseSort: 0,
  };
  proxy.resetForm("formRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  // fix 选择直接指定
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = "添加课程";
}
/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}
/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  queryOne(row.id).then((response) => {
    form.value = response;
    // fix 更新
    if (response.parent != null) {
      form.value.parentId = response.parent.id;
    } else {
      form.value.parentId = 0;
    }

    open.value = true;
    title.value = "修改课程";
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateOne(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        createOne(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除名称为"' + row.courseName + '"的数据项?')
    .then(function () {
      return deleteOne(row.id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

getList();
</script>
